<?php

namespace App\Components\Twig;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\App;
use Slim\Interfaces\RouteParserInterface;

class TwigMiddleware implements MiddlewareInterface
{
    protected $twig;

    protected $routeParser;

    protected $basePath;

    protected $attributeName;

    public function __construct(
        Twig $twig,
        RouteParserInterface $routeParser,
        string $basePath = '',
        ?string $attributeName = null
    ) {
        $this->twig = $twig;
        $this->routeParser = $routeParser;
        $this->basePath = $basePath;
        $this->attributeName = $attributeName;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $runtimeLoader = new TwigRuntimeLoader($this->routeParser, $request->getUri(), $this->basePath);
        $this->twig->addRuntimeLoader($runtimeLoader);

        if ($this->attributeName !== null) {
            $request = $request->withAttribute($this->attributeName, $this->twig);
        }

        return $handler->handle($request);
    }

    public static function create(App $app, Twig $twig, string $attributeName = 'view'): self
    {
        return new self(
            $twig,
            $app->getRouteCollector()->getRouteParser(),
            $app->getBasePath(),
            $attributeName
        );
    }
}
